package com.itcast.googleplay;

import java.io.File;

import com.itcast.googleplay.domain.AppInfo;
import com.itcast.googleplay.holder.AppDesHolder;
import com.itcast.googleplay.holder.AppInfoHolder;
import com.itcast.googleplay.holder.AppPicHolder;
import com.itcast.googleplay.holder.AppSafeHolder;
import com.itcast.googleplay.protocol.DetailProtocol;
import com.itcast.googleplay.ui.LoadingPage;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.HttpHandler.State;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;
import com.lidroid.xutils.sample.download.DownloadService;
import com.lidroid.xutils.util.LogUtils;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class DetailActivity extends BaseActivity {
	private static final String TAG = "DetailActivity";
	private String packageName;
	private AppInfo data;
	private ScrollView scrollView;
	private ProgressBar pbBar;
	//下载过程中的状态监听?因为状态的切换,必然涉及UI的变化,所以需要对状态监听
	private DownloadStateListener downloadStateListener = new DownloadStateListener();
	 private DownloadManager downloadManager = DownloadService.getDownloadManager(UIUtils.getContext());
	private TextView tvStateText;
	
	/** 下载状态监听器  */
    private class DownloadStateListener extends RequestCallBack<File> {

    	/** 下载失败 */
		@Override
		public void onFailure(HttpException arg0, String arg1) {
			refreshUI();
		}

		/** 下载成功 */
		@Override
		public void onSuccess(ResponseInfo<File> arg0) {
			refreshUI();
		}

		/** 取消下载 ,即暂停*/
		@Override
		public void onCancelled() {
			refreshUI();
		}

		/** 正在下载*/
		@Override
		public void onLoading(long total, long current, boolean isUploading) {
			refreshUI();
		}

		/** 开始下载 */
		@Override
		public void onStart() {
			refreshUI();
		}
		
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		packageName = getIntent().getStringExtra("packagename");
		Log.i(TAG, "====================packageName = "+packageName);
		initActionBar();
		
		LoadingPage loadingPage = new LoadingPage(UIUtils.getContext()) {
			
			@Override
			public ResultState onLoad() {
				return onDetailLoad();
			}
			
			@Override
			public View onCreateSuccessedView() {
				return onDetialSuccessedView();
			}
		};
		
		//使用loadingPage调用show方法,show方法开启子线程调用onLoad方法,onLoad方法调用了onDetailLoad方法请求网络就被触发
		if(loadingPage!=null){
			loadingPage.show();
		}
		//此方法等同于setContentView(R.layout.xxxx)
		//以下方法将LoadingPage设置给当前的activity,即维护了4中网络请求状态的帧布局设置给了当前activity
		setContentView(loadingPage);
	}

	public void refreshUI() {
    	DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
    	if (downloadInfo == null) {
			// 如果原来没有下载过，则显示成下载
    		tvStateText.setText("点击就下载");
//    		pbBar.setProgress(0);进度条如果碰到的应用是没有下载过的,必须是0
		}else{
			 HttpHandler.State state = downloadInfo.getState();	// 获取当前下载信息的下载状态
		        switch (state) {
		        case WAITING:
		        	//1.如果状态是等待
		        	//按钮的文字显示成等待
		        	tvStateText.setText("等待");
		        	break;
		        case STARTED:
		        	//2.如过状态是开始下载
		        	tvStateText.setText("开始下载");
		        	//按钮的文字显示成开始下载
		        	break;
		        case LOADING:
		        	if(downloadInfo.getFileLength()>0){
		        		//3.如过状态是正在下载
			        	//计算进度条的百分比(当前下载位置+0.0f/总进度  = 0)
			        	int loadingProgress = (int) (downloadInfo.getProgress()*100/downloadInfo.getFileLength());
			        	//按钮显示文字百分比进度条
			        	tvStateText.setText(loadingProgress+"%");
			        	pbBar.setProgress(loadingProgress);
		        	}
		        	
		        	break;
		        case CANCELLED:
		        	if(downloadInfo.getFileLength()>0){
		        		//4.如果状态是暂停
			        	//按钮的显示文字暂停,为了提示用户可以接着下载"暂停"两个字改成"继续"
			        	
			        	int loadingProgress1 = (int) (downloadInfo.getProgress()*100/downloadInfo.getFileLength());
			        	tvStateText.setText("点击继续");
			        	pbBar.setProgress(loadingProgress1);
		        	}
		        	break;
		        case SUCCESS:
		        	//5.如果状态是成功
		        	//按钮显示文字安装
		        	tvStateText.setText("点击安装");
		        	break;
		        case FAILURE:
		        	//6.如果状态是失败
		        	//按钮显示文字重新下载(重试)
		        	tvStateText.setText("点击重试");
		        	break;
		        }
		}
    	
       
    
	}

	private void initActionBar() {
		//1.获取actionBar对象
		ActionBar actionBar = getSupportActionBar();
		//2.修改actionBar图片和文字
		actionBar.setTitle("传智一期谷歌市场");
		actionBar.setIcon(R.drawable.ic_launcher);
		
		//3.设置左上角三条线的图片可见,此段api必须和setDisplayHomeAsUpEnabled一起使用,否则无效
		actionBar.setDisplayShowHomeEnabled(true);
		//4.设置actionBar左上角的按钮可以使用
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == android.R.id.home){
//			Toast.makeText(UIUtils.getContext(), "结束activity界面", 0).show();
			finish();
		}
		return super.onOptionsItemSelected(item);
	}

	protected View onDetialSuccessedView() {
		View view = UIUtils.inflate(R.layout.activity_detail);
		
		scrollView = (ScrollView) view.findViewById(R.id.scv);
		
		//描述信息所在的帧布局逻辑
		FrameLayout flAppInfo = (FrameLayout) view.findViewById(R.id.fl_app_info);
		//1.创建holder对象,让其继承至BaseHolder
		AppInfoHolder appInfoHolder = new AppInfoHolder();
		//2.给holder传递数据,让initData方法可以使用数据填充控件
		appInfoHolder.setData(data);
		//3.添加AppInfoHolder在initView方法返回的页面效果
		flAppInfo.addView(appInfoHolder.getConvertView());
		
		
		//可扩展的安全信息帧布局的相关逻辑
		FrameLayout flAppSafe = (FrameLayout) view.findViewById(R.id.fl_app_safe);
		AppSafeHolder appSafeHolder = new AppSafeHolder();
		appSafeHolder.setData(data);
		flAppSafe.addView(appSafeHolder.getConvertView());
		
		FrameLayout flAppPic = (FrameLayout) view.findViewById(R.id.fl_app_pic);
		AppPicHolder appPicHolder = new AppPicHolder();
		appPicHolder.setData(data);
		flAppPic.addView(appPicHolder.getConvertView());
		
		FrameLayout flAppDes = (FrameLayout) view.findViewById(R.id.fl_app_des);
		AppDesHolder appDesHolder = new AppDesHolder();
		appDesHolder.setScrollView(scrollView);
		appDesHolder.setData(data);
		flAppDes.addView(appDesHolder.getConvertView());
		
		tvStateText = (TextView) view.findViewById(R.id.tv_state_text);
		
		pbBar = (ProgressBar) view.findViewById(R.id.pb_bar);
		
		
		//给进度条注册点击事件
		pbBar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				download();
			}
		});
		//展示初始状态的操作,所以调用refreshUI方法
		refreshUI();
		//在此进入此页面的是,进行下一次的监听过程,如果不加此方法,在此进入页面进度条不会更新
		registerProgressUpdate();
		
		return view;
	}

	protected void download() {
		//根据一个应用的id获取一个应用的下载信息(应用当前的下载到的位置,下载应用的名称,包名,唯一性id,下载应用的总大小)
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
		if(downloadInfo == null){
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//				String target = Environment.getExternalStorageDirectory()+"/googleplay0818/download/"+data.name+".apk";
				String target = Environment.getExternalStorageDirectory()
						+File.separator+"googleplay0818"
						+File.separator+"download"
						+File.separator
						+data.name+".apk";
				String appUrl = "http://127.0.0.1:8090/download?name="+data.downloadUrl;
				try {
					downloadManager.addNewDownload(data.id+"", 
							appUrl,
							data.name,  // 保存到数据库时候的一个应用名称
					        target,		// 指定保存路径和保存的文件名
					        true, 		// 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
					        false, 		// 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
					        downloadStateListener);// 用于接收下载状态的监听器
				} catch (DbException e) {
					e.printStackTrace();
				}		
			}
		}else{
			// 如果原来下载过，则要么暂停，要继续
			HttpHandler.State state = downloadInfo.getState();
            switch (state) {
                case WAITING:
                case STARTED:
                case LOADING:
                	// 如果原来是等待、开始、正在下载，则暂停
                    try {
                        downloadManager.stopDownload(downloadInfo);	// 暂停下载
                    } catch (DbException e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                    break;
                case CANCELLED://pause(暂停)
                case FAILURE:
                	// 如果原来暂停了下载，或者下载失败了，则重新下载，如果暂停的话是断点续传地下载
                    try {
                        downloadManager.resumeDownload(downloadInfo, downloadStateListener);	// 第二个参数用于接收下载状态
                    } catch (DbException e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                    break;
                case SUCCESS:
                	//安装应用,调用系统的activity安装
                	installApk();
                	break;
                default:
                    break;
            }
            //此方法是在重头下载后,或者根据记录状态接着下载后,立马刷新UI的方法
            refreshUI();
		}
	}
	
	private void installApk() {
		Intent intent = new Intent("android.intent.action.VIEW");
		//匹配category
		intent.addCategory("android.intent.category.DEFAULT");
		//匹配data数据源
		//匹配数据类型
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
		intent.setDataAndType(Uri.parse("file://"+downloadInfo.getFileSavePath()),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

	protected ResultState onDetailLoad() {
		DetailProtocol detailProtocol = new DetailProtocol();
		data = detailProtocol.getData("detail", -1, "packageName="+packageName);
		if(data != null){
			return ResultState.STATE_SUCCESSED;
		}
		return ResultState.STATE_ERROR;
	}
	
	private void registerProgressUpdate() {
	    //获取下载的javabean对象
	    DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.id+"");
	     //此对象如果不为空，则说明之前下载过，在回到activity界面的时候，需要再次对下载状态进行监听
	     if(downloadInfo!=null){
	         HttpHandler<File> handler = downloadInfo.getHandler();
	         if (handler != null) {
	             RequestCallBack callBack = handler.getRequestCallBack();
	             if (callBack instanceof DownloadManager.ManagerCallBack) {
	                 DownloadManager.ManagerCallBack managerCallBack = (DownloadManager.ManagerCallBack) callBack;
	                 if (managerCallBack.getBaseCallBack() != null) {
	                     //再次让监听器生效
	                     managerCallBack.setBaseCallBack(downloadStateListener);
	                 }
	             }
	         }
	     }
	}

}
